<template>
    <div style="height:100%">
        <Tabs closable v-model="name" type="card" style="height:100%" @on-tab-remove="handleTabRemove" :animated="false">
            <TabPane name="namedefault" label="房源列表" :closable='false'>
                <Card class="no-border-card">
                    <p slot="title">
                        房源列表
                    </p>
                    <Button
                        class="btn-in-top-large"
                        style="margin-right:105px;"
                        @click="exportHouseDtail()" type="primary">
                        导出房源明细
                    </Button>
                    <Button
                        slot="extra"
                        v-pmis="21"
                        class="btn-in-top-large"
                        style="margin-right:-15px;"
                        @click="addHouse()" type="primary">
                        添加房源
                    </Button>

                    <search-component
                        @search="handleSearch"></search-component>

                    <div class="margin-bottom-20"  v-if="!isKeeper">
                        <Button style="padding:7px 10px 8px;margin-right:12px;">
                            <Checkbox label="全选" class="select-all-house" @on-change="handleSelectAll">
                                全选
                            </Checkbox>
                        </Button>
                        <!-- <Button @click="handleSelectAll(false)">取消全选</Button> -->

                        <Button type="primary" @click="handleManage">更改管理者</Button>
                    </div>

                    <Table
                        style="margin-top:8px;"
                        ref="selection"
                        class="no-btn-border"
                        :columns="columns"
                        :data="data4"
                        :loading="tableLoading"
                        @on-selection-change="handleSelect"></Table>

                    <Page
                        @on-change="getHomes"
                        :total="total"
                        :page-size="form.limit"
                        show-elevator show-total
                        :current.sync="form.offset"
                        style="text-align:center">
                    </Page>
                </Card>
            </TabPane>

            <TabPane name="create-focus" label="新建集中式" v-if="showCreateFocus">
                <create-focus @success="handleCreated"></create-focus>
            </TabPane>

            <TabPane
                v-for="home in editFocusHomeTabs"
                :key="home.id"
                :name="home.tabName"
                :label="home.tabLabel">
                <edit-focus :home="home" @success="handleCreated"></edit-focus>
            </TabPane>

            <!-- tab循环 -->
            <TabPane
            v-for="tab in tabs"
            :name="'name' + tab.id"
            :key="'name' + tab.id"
            :label="tab.home_name + (tab.home_type==1 ? '-分散式':'-集中式')">
                <!-- <focus-float
                v-if="tab.home_type==2"
                :homeId="tab.created_at ? tab : null"
                @update="update"></focus-float> -->

                <split-float
                v-if="tab.home_type==1"
                :homeId="tab.created_at ? tab : null"
                @update="update"></split-float>
            </TabPane>

        </Tabs>
        <Modal v-model="modal" title="选择类型" class="empty-footer" class-name="vertical-center-modal">
            <Row type="flex" justify="space-around" class="code-row-bg" style="height:120px;margin-top: -18px;">
                <Col span="12" style="display:flex;align-items:center;justify-content: flex-end;padding-right:10px">
                    <span class="house-type-btn" style="cursor:pointer;" @click="showSplit">分散式公寓</span>
                </Col>
                <Col span="12" style="display:flex;align-items:center;justify-content: flex-start;padding-left:10px">
                    <span class="house-type-btn" style="cursor:pointer;" @click="showFocus">集中式公寓</span>
                </Col>
            </Row>
            <p slot="footer">
            </p>
        </Modal>

        <Modal
            title="更改管理者"
            v-model="selectModal.manageVisible">

            <Form :label-width="80" style="padding-right:20px;padding-top:22px;">
                <FormItem label="已选房源">
                    <Tag
                        v-for="branch in selectionInfo"
                        :key="branch.id">
                        {{branch.home_name}}
                    </Tag>
                </FormItem>
                <FormItem label="房源归属">
                    <!-- 这个选项不影响接口字段,产品作为区分总部来使用 -->
                    <Select
                        v-model="selectModal.parentHome"
                        @on-change="handleParentChange"
                        placeholder="选择分店">
                        <Option :value="1">总部</Option>
                        <Option :value="2">分店</Option>
                    </Select>
                </FormItem>
                <FormItem
                    label="所选门店">
                    <Select
                        clearable
                        filterable
                        :disabled="selectModal.parentHome === 1"
                        @on-change="handleFetchKeeper"
                        v-model="selectModal.branchId"
                        placeholder="选择分店">
                        <Option v-for="item in branches" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="管家">
                    <Select
                        filterable
                        multiple
                        v-model="selectModal.keeper"
                        placeholder="选择管家">
                        <Option
                            v-for="item in selectModal.keepers"
                            :value="item.id"
                            :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="text" @click="selectModal.manageVisible = false">取消</Button>
                <Button
                    type="primary"
                    :loading="selectModal.loading"
                    @click="handleDistribution">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
// import focusFloat from './focus/focusFloat.vue';
import createFocus from './focus/create-focus'
import editFocus from './focus/edit-focus'
import splitFloat from './split/splitFloat.vue'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
import searchComponent from './components/search-component'
import util from '@/libs/util'

export default {
  name: 'home-list',
  components: {
    editFocus,
    createFocus,
    // focusFloat,
    splitFloat,
    searchComponent
  },
  data () {
    return {
      editFocusHomeTabs: [], // 编辑集中式房源标签
      showCreateFocus: false,
      tabs: [],
      name: 'namedefault',
      tableLoading: false,
      form: {
        offset: 1,
        limit: 20,
        tag: '', // 省市区region_code
        keyword: '',
        home_type: '',
        branch_id: '',
        user_id: ''
      },
      total: 0,
      branches: [],
      branch: [],
      modal: false,
      home_types: [],
      keeperId: '',
      branchId: '',
      data4: [],
      selection: [],
      selectionInfo: [], // 已选全部信息
      selectModal: {
        manageVisible: false,
        keepers: [],
        keeper: [],
        branch: '',
        branchId: '',
        parentHome: 1,
        loading: false
      }
    }
  },
  computed: {
    isKeeper () {
      const { roleId } = this.$store.state.user
      return roleId === 104 || roleId === 103
    },
    userHasBranchs () {
      const { branches } = this.$store.state.user
      return !!branches.length
    },
    columns () {
      const data = [
        {
          title: '房源编号',
          key: 'home_name',
          align: 'center'
        },
        {
          title: '公寓类型',
          width: 100,
          key: 'home_type',
          align: 'center',
          render: (h, params) => {
            return h('p', params.row.home_type === 1 ? '分散式' : '集中式')
          }
        },
        {
          title: '公寓地址',
          key: 'address',
          align: 'center',
          minWidth: 200,
          render: (h, params) => {
            let concatedLocation = util.concatLocation(params.row)
            return h('span', concatedLocation)
          }
        },
        {
          title: '房间数量',
          key: 'room_count',
          width: 100,
          align: 'center'
        },
        {
          title: '所属分店',
          key: 'branch_id',
          align: 'center',
          render: (h, params) => {
            return h('p', this.branches ? this.getBranch(params.row.branch_id) : '')
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 140,
          align: 'center',
          render: (h, p) => (<i-button v-pmis={21} type='ghost' size='small' onClick={() => this.edit(p.row)}>编辑</i-button>)
        }
      ]
      if (!this.isKeeper) {
        data.unshift({
          type: 'selection',
          width: 60,
          align: 'center'
        })
      }
      return data
    }
  },
  mounted () {
    this.getHomes()
    this.getbranches()
  },
  methods: {
    handleCreated () {
      this.showCreateFocus = false
      this.name = 'namedefault'
      this.getHomes()
    },
    /**
         * 更改门店, 管家
         * 如果不选择管家, 调用更改门店接口
         */
    handleDistribution () {
      if (this.selectModal.keeper.length === 0) {
        this.changeBranch()
        return
      }
      const data = {
        home_ids: this.selection,
        branch_id: this.selectModal.branchId || null,
        user_ids: this.selectModal.keeper
      }
      this.selectModal.loading = true
      http.request(this, api.home_users, null, data, (res, err) => {
        if (err || !res) {
          this.$Message.error(err.data.err_msg)
        } else {
          this.$Message.success('操作成功')
          this.cleanModalAfterChange()
        }
        this.selectModal.loading = false
      })
    },
    async changeBranch () {
      try {
        this.selectModal.loading = true
        const data = {
          home_ids: this.selection,
          branch_id: this.selectModal.branchId
        }
        await http.req(api.home_update_brance, null, data)
        this.$Message.success('操作成功')
        this.cleanModalAfterChange()
      } catch (err) {
        console.log(err)
      } finally {
        this.selectModal.loading = false
      }
    },
    cleanModalAfterChange () {
      this.selectModal.manageVisible = false
      this.selectModal.keeper = []
      this.selectModal.branchId = []
      this.selection = []
      this.selectionInfo = []
      this.$refs.selection.selectAll(false)
      this.getHomes()
    },
    handleFetchKeeper (id) {
      if (id === undefined) return
      this.selectModal.keepers = []
      this.selectModal.keeper = []
      const query = {
        offset: 0,
        limit: 1000,
        role_id: 104,
        branch_id: id || null,
        list_type: 'all'
      }
      http.request(this, api.user_list, null, query, (res, err) => {
        if (err) {
          this.$Message.error('获取管家列表失败')
        } else {
          let datas = res.rows
          if (id === 0) {
            datas = datas.filter(keeper => keeper.branches.length === 0)
          }
          this.selectModal.keepers = datas
        }
      })
    },
    handleParentChange (value) {
      this.selectModal.branchId = 0
      this.selectModal.keepers = []
      this.selectModal.keeper = []
      if (value === 1) {
        this.handleFetchKeeper(0)
      }
    },
    /**
         * 解析当前选择的selectionInfo列表,
         * 当去重后的branch_id数组为1时可以继续操作, 打开'更改管理者'窗口
         */
    handleManage () {
      const selectItem = [...new Set(this.selectionInfo.map(home => home.branch_id))]
      if (selectItem.length === 0) {
        this.$Message.info('请先选择房源')
      } else if (selectItem.length > 1) {
        this.$Message.info('请选择同一门店的房源')
      } else {
        this.selectModal.branchId = selectItem[0]
        this.handleFetchKeeper(this.selectModal.branchId)
        if (this.selectModal.branchId !== 0) {
          this.selectModal.parentHome = 2
        }
        this.selectModal.manageVisible = true
      }
    },
    edit (home) {
      if (home.home_type === 2) {
        const homeAdded = this.editFocusHomeTabs.find(h => h.id === home.id)
        if (homeAdded) {
          this.name = homeAdded.tabName
        } else {
          const tabName = `editFocusHomeTabs-x-${home.id}`
          this.editFocusHomeTabs.push({
            ...home,
            tabName,
            tabLabel: `${home.home_name}-集中式`
          })
          this.name = tabName
        }
      } else {
        const homeExists = this.tabs.some(item => home.id === item.id)

        if (homeExists) {
          this.name = 'name' + home.id
        } else {
          this.tabs.push(home)
          this.name = 'name' + home.id
        }
      }
    },
    handleTabRemove (name) {
      if (name === 'create-focus') {
        this.showCreateFocus = false
        this.name = 'namedefault'
      } else if (name.includes('editFocusHomeTabs')) {
        const homeId = Number(name.split('-x-')[1])
        const homeTabIndex = this.editFocusHomeTabs.findIndex(h => h.id === homeId)
        this.editFocusHomeTabs.splice(homeTabIndex, 1)
        this.name = 'namedefault'
      } else {
        let removeIndex
        this.tabs.forEach((item, idx) => {
          if ('name' + item.id === name) {
            removeIndex = idx
          }
        })
        this.tabs.splice(removeIndex, 1)
        if (removeIndex === 0) {
          this.name = 'namedefault'
        } else {
          this.name = 'name' + this.tabs[removeIndex - 1].id
        }
      }
    },
    update (type, doNotRemove) {
      if (!doNotRemove) {
        this.handleTabRemove('name' + type)
      }
      this.getHomes()
    },
    showFocus () {
      this.showCreateFocus = true
      this.modal = false
      this.name = 'create-focus'
      // this.modal = false;
      // let param = {
      //     row: {
      //         id: 'focus',
      //         home_type: 2,
      //         home_name: '新建'
      //     }
      // };
      // this.edit(param);
    },
    showSplit () {
      this.modal = false
      let param = {
        id: 'split',
        home_type: 1,
        home_name: '新建'
      }
      this.edit(param)
    },
    handleSearch (searchData) {
      this.form = {
        offset: 1,
        limit: 20,
        ...searchData
      }
      this.getHomes()
    },
    // 获取某个门店
    getBranch (id) {
      if (!id) {
        return '总部'
      }
      for (let i = 0; i < this.branches.length; i++) {
        let item = this.branches[i]
        if (item['id'] === id) {
          return item.name
        }
      }
    },
    // 获取房源列表
    getHomes () {
      this.tableLoading = true
      // console.log(this.form);
      const data = util.cleanObj(this.form, [0])
      data.offset = (data.offset - 1) * data.limit
      http.request(this, api.home_list, null, data, (res, err) => {
        this.tableLoading = false
        if (err || !res) {
          return
        }
        this.data4 = res.homes
        this.total = res.count
      })
    },
    addHouse () {
      this.modal = true
      //  this.$router.push({ name: "house_detail" });
    },
    // 导出房源明细
    exportHouseDtail () {
      const { home_type, branch_id, tag, keyword, user_id } = this.form
      const params = util.cleanObj({
        download: true,
        home_type,
        branch_id,
        tag,
        keyword,
        user_id
      })
      http.exportTable(this, api.export_homes_detai, null, params)
    },

    handleSelectAll (status) {
      this.$refs.selection.selectAll(status)
    },
    handleSelect (selection) {
      this.selectionInfo = selection
      selection = selection.map(item => {
        return item.id
      })
      this.selection = selection
    },
    // 获取门店
    getbranches () {
      dataCenter.getStores(this, (res, err) => {
        if (err || !res) {
          return
        }
        this.branches = res
      })
    }
  }
}
</script>
<style lang="less">
.ivu-card-head p {
    height: auto;
}

.ivu-card-head {
    padding-top: 8px;
    padding-bottom: 6px;
}
.house-type-btn {
    border: 1px solid #b5b5b5;
    padding: 10px 27px;
    border-radius: 4px;
    &:hover {
        color: #fff;
        background-color: #05bac5;
    }
}

.f-room {
    &-box {
        display: flex;
        height: 38px;
        border-radius: 4px;
        border: 1px solid #bbb;
        background-color: #fff;
        overflow: hidden;
        .ivu-input {
            border: 0;
        }
        .ivu-input:focus {
            box-shadow: none;
        }
        &.is-special {
            background-color: #ccc;
        }
    }
    &-prepend,
    &-append {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 38px;
        &:hover {
            background-color: #eee;
        }
    }
    &-prepend {
        border-right: 1px solid #bbb;

        &.no-border {
            border-right: 0;
        }
    }
    &-content {
        flex: 1;
        padding: 0 10px;
        line-height: 36px;
    }
    &-append {
        border-left: 1px solid #bbb;
    }
}

.r-split {
    &-wrap {
        padding: 40px 10px 40px 10px;
        border-left: 5px solid #05bac5;
        background-color: #efeff1;
    }

    &-container {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: -20px;
    }

    &-item {
        display: flex;
        flex: 0 1 25%;
        margin-bottom: 20px;
        padding: 0 5px;
        &-main {
            flex: 1;
        }

        &-extra {
            width: 80px;
            padding-left: 10px;
        }

        & .is-hide-btn {
            display: none;
            transition: all 0.6s;
            &:hover {
                background-color: #fff;
            }
        }

        &:hover {
            .is-hide-btn {
                display: inline-block;
            }
        }
    }
}
.floor-item {
    margin-top: 10px;
}
</style>
